/**
 * 选择了ak或使用IP白名单校验：
 */

package cn.neusoft.util;

import cn.neusoft.enums.ScheduleStrategy;
import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.IntStream;

@Data
public class BaiduMapUtils {

    private static String AK = "3hko5g9f4YGRPQBGR4Krll8wGQ5n3GiE";


//    public static void main(String[] args) throws Exception {
//
//        BaiduMapUtils baiduMapUtils = new BaiduMapUtils();
//
//        Map params = new LinkedHashMap<String, String>();
////        params.put("address", "北京市海淀区上地十街10号");
////        params.put("output", "json");
////
////        baiduMapUtils.geoCoding(params);
//
//        params.put("origins", "40.45,116.34|40.47,120.34");
//        params.put("destinations", "40.34,116.45");
//
//        baiduMapUtils.routeMatrix(params, ScheduleStrategy.AUTO_BY_DURATION.getCode());
//    }

    // 请求接口
    private static JSONObject requestApi(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        param.put("ak", AK);

        StringBuilder queryString = new StringBuilder();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey()).append("=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8")).append("&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString);
        URLConnection httpConnection = url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        System.out.println("AK: " + buffer);

        // 将api返回的json字符串转成json对象
        JSONObject response = JSON.parseObject(buffer.toString());

        return response;
    }


    // 调用批量算路api
    public static int routeMatrix(Map<String, String> param, Integer scheduleStrategy) throws Exception {
        String URL = "https://api.map.baidu.com/routematrix/v2/driving?";
        JSONObject response = requestApi(URL, param);

        // api异常
        if (!Objects.equals(response.get("status"), 0)) {
            throw new AppException(AppExceptionCodeMsg.BAIDU_MAP_API_ERROR);
        }

        JSONArray resultArray = response.getJSONArray("result");

        String strategy;

        // 耗时优先
        if (Objects.equals(scheduleStrategy, ScheduleStrategy.AUTO_BY_DURATION.getCode())) {
            strategy = "duration";
        } else { // 距离优先
            strategy = "distance";
        }

        int bestIndex = IntStream.range(0, resultArray.size())
                .boxed()
                .min(Comparator.comparingInt(i -> resultArray.getJSONObject(i).getJSONObject(strategy).getIntValue("value")))
                .orElse(-1);

        System.out.println("最佳分站的下标为：" + bestIndex);

        return bestIndex;
    }

    // 调用地理编码api
    public static String geoCoding(Map<String, String> param) throws Exception {
        String URL = "https://api.map.baidu.com/geocoding/v3?";
        JSONObject response = requestApi(URL, param);

        // api异常
        if (!Objects.equals(response.get("status"), 0)) {
            throw new AppException(AppExceptionCodeMsg.BAIDU_MAP_API_ERROR);
        }

        JSONObject location = response.getJSONObject("result").getJSONObject("location");

        // 坐标格式为：纬度,经度
        String coordinate = location.get("lat").toString() + "," + location.get("lng").toString();

        System.out.println(coordinate);

        return coordinate;
    }

}